package com.fin.quant.domain.repository.impl;

import com.fin.quant.domain.entity.AiMessagesEntity;
import com.fin.quant.domain.mapstruct.AiMessagesMapperStruct;
import com.fin.quant.domain.repository.MessageRepository;
import com.fin.quant.instra.mysql.mapper.AiMessagesMapper;
import com.fin.quant.instra.mysql.model.AiMessages;
import com.fin.quant.instra.mysql.model.AiMessagesExample;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageRepositoryImpl implements MessageRepository {

    @Autowired
    private AiMessagesMapper aiMessagesMapper;

    @Override
    public AiMessagesEntity saveOrUpdate(AiMessagesEntity message) {
        if (message == null) {
            throw new IllegalArgumentException("Message entity cannot be null");
        }

        AiMessages model = AiMessagesMapperStruct.INSTANCE.entityToModel(message);

        if (message.getId() == null) {
            // Insert new message
            aiMessagesMapper.insertSelective(model);
        } else {
            // Update existing message
            aiMessagesMapper.updateByPrimaryKeySelective(model);
        }

        return AiMessagesMapperStruct.INSTANCE.modelToEntity(model);
    }

    @Override
    public List<AiMessagesEntity> findByConversationIdOrderByCreatedAtAsc(String conversationId) {
        if (conversationId == null || conversationId.isEmpty()) {
            return Collections.emptyList();
        }

        AiMessagesExample example = new AiMessagesExample();
        example.createCriteria().andConversationIdEqualTo(conversationId);
        example.setOrderByClause("created_at ASC");

        List<AiMessages> messages = aiMessagesMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(messages)) {
            return Collections.emptyList();
        }

        return messages.stream()
                .map(AiMessagesMapperStruct.INSTANCE::modelToEntity)
                .collect(Collectors.toList());
    }
}
